Could you guys post a professional review of these crons?

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Could you guys post a professional review of these crons?

Post by josh »

FYI I did not write them :D

The first one is called DailyTasks.php, thats the only hint you get.

Code: Select all

 
<?
include("/home/example/public_html/resources/dbconnect.php");
include("/home/example/public_html/cgi-bin/EmailFunctions.php");
 
$today = date("Y-m-d");
$filename = "/home/example/public_html/cgi-bin/logs/dailytasks_cron.txt";
$fp = fopen($filename , "a") or die("couldnt open file to  write");
$appendText = "\n*******************************************\n";
$appendText .= "Date : " . date("m/d/Y");
//echo "In Closed Jobs";
$appendText .= "\n========================================\n";
$appendText .= "Sent Emails to following employers for closing the Specific Dates Jobs \n";
$appendText .= "-------------------------------------------------------------------------\n";
//**************************************************
 
///make job postings deadlines  close  for the one s with specific date when they reach today's date.
$SQL = "select employer.id as empid, firstname, lastname, email, empName, positionname, created, jobid, edited from employerjob " ;
$SQL .= ", employer, address where deadline = 1   and deadlinedate < '$today'";
$SQL .= " and employerjob.empid =  employer.id and employer.addressid = address.id";
$result = mysql_query($SQL) or die("select result1 failed");
while ($row=mysql_fetch_array($result)){
    $SQL1= "update employerjob set deadline = 3, edited = '$today',  priority =0 where jobid = ". $row['jobid'];
    mysql_query($SQL1) or die("Update in employerjob table for deadline=1 failed");
 
    $SQL5 = "update employer set jobsclose = jobsclose+1 where id = " . $row['empid'];
    mysql_query($SQL5) or die("update in employer table for close failed");
 
    $SQL5 = "update employer set jobsspecific = jobsspecific-1 where id = " . $row['empid'];
    mysql_query($SQL5) or die("update in employer table for specific jobs failed");
 
    //echo "SQL2 : " . $SQL1 . "<br>";
    $contactName = $row['firstname']. " " . $row['lastname'];
    $empname =  $row['empName'];
    $jobtitle = $row['positionname'];
    $dateAr = explode("-",$row['edited']);
    $date = $dateAr[1]."/".$dateAr[2]."/".$dateAr[0];   
    $email  = $row['email'];
    sendClosedEmail($email, $contactName,$empname, $jobtitle, $date);
    //$appendText .= $empname . "\t" . $email . "\n";
    $appendText .= $empname . "\t" . $jobtitle . "\n";
}
$appendText .= "========================================\n\n";
$appendText .= "Sent Emails to following employers for closing 90 days after the Open Until Filled Jobs \n";
$appendText .= "-------------------------------------------------------------------------------------------\n";
 
//**************************************************
//make job postings deadlines close after 90 days of creating it for the ones whose deadline is Open Until Filled 
$proposed =  mktime(0,0,0,date("m") ,  date("d")-90,  date("Y"));
$proposed = date("Y-m-d", $proposed);
$SQL = "select employer.id as empid, firstname, lastname, email, empName, positionname, created, jobid, edited from employerjob " ;
$SQL .= " , employer, address where deadline = 2   and edited < '$proposed'";
$SQL .= " and employerjob.empid =  employer.id and employer.addressid = address.id";
$result = mysql_query($SQL) or die("select result2 failed");
//echo "SQL3 : " . $SQL. "<br>";
while ($row=mysql_fetch_array($result)){
    $SQL1= "update employerjob set deadline = 3 , edited = '$today',  priority = 0 where jobid = ". $row['jobid'];
    //echo "SQL4 : " . $SQL1 . "<br>";
    mysql_query($SQL1) or die("Update in employerjob table for deadline=2 failed");
    $SQL5 = "update employer set jobsclose = jobsclose+1 where id = " . $row['empid'];
    mysql_query($SQL5) or die("update in employer table for close failed");
 
    $SQL5 = "update employer set jobsopen = jobsopen-1 where id = " . $row['empid'];
    mysql_query($SQL5) or die("update in employer table for specific jobs failed");
 
    $contactName = $row['firstname']. " " . $row['lastname'];
    $empname =  $row['empName'];
    $jobtitle = $row['positionname'];
    $dateAr = explode("-",$row['edited']);
    $date = $dateAr[1]."/".$dateAr[2]."/".$dateAr[0];   
    $email  = $row['email'];
    sendClosedEmail($email, $contactName,$empname, $jobtitle, $date);
    //$appendText .= $empname . "\t" . $email . "\n";
    $appendText .= $empname . "\t" . $jobtitle . "\n";
 
}
//************************************************
//deleting saved resumes 3 months after the job is closed.
$proposed =  mktime(0,0,0,date("m")-3 ,  date("d"),  date("Y"));
$proposed = date("Y-m-d", $proposed);
$SQLSaved= " select * from employerjob where deadline=3 and edited <= '$proposed'";
$result = mysql_query($SQL) or die("select employer job for saved resumes failed");
//echo "SQL5 : " . $SQLSaved . "<br>";
while ($row=mysql_fetch_array($result)){
$SQL2= "delete from savedresumes where jobid = ". $row['jobid'];
    mysql_query($SQL2) or die("Delete From Saved Resumes table for deadline=2 failed");
    //echo "SQL6 : " . $SQL2 . "<br>";
}
//echo $appendText . "<br>";
 
//**************************************************
 
//echo "In emailAbtToExpire<br>";
 
//send emails to employers 45 days before the account expires
$appendText .= "========================================\n\n";
$appendText .= "Sent Emails to following employers for 45 days before the account expires\n";
$appendText .= "-------------------------------------------------------------------------------------------\n";
 
 
$proposed = mktime(0,0,0,date("m") ,  date("d")+45,  date("Y"));
$proposed = date("Y-m-d", $proposed);
$SQLAbtToexpire = "select employer.id, username, password,empName,firstname,lastname,email from employer,address where expirydate = '$proposed' and employer.addressid = address.id";
//echo "SQL7 : " . $SQLAbtToexpire . "<br>";
$resultAbtToexpire = mysql_query($SQLAbtToexpire) or die("select resultAbtToexpire1 failed");
while ($rowAbtToexpire = mysql_fetch_array($resultAbtToexpire)){
    // send reminder emails. 
    emailAboutToExpire($rowAbtToexpire['email'],$rowAbtToexpire['username'],$rowAbtToexpire['password'],$rowAbtToexpire['firstname'],$rowAbtToexpire['lastname'],$rowAbtToexpire['empName']);
    //echo "SQL8 : In send  Emails to ALl About To expire" . "<br>";
    $appendText .= $rowAbtToexpire['empName'] . "\t" . $rowAbtToexpire['email'] . "\n";
 
}
//**************************************************
//send emails to employers 30 days before the account expires
$appendText .= "========================================\n\n";
$appendText .= "Sent Emails to following employers for 30 days before the account expires\n";
$appendText .= "-------------------------------------------------------------------------------------------\n";
 
 
$proposed = mktime(0,0,0,date("m") ,  date("d")+30,  date("Y"));
$proposed = date("Y-m-d", $proposed);
$SQLAbtToexpire = "select employer.id, username, password,empName,firstname,lastname,email from employer,address where expirydate = '$proposed' and employer.addressid = address.id";
$resultAbtToexpire = mysql_query($SQLAbtToexpire) or die("select resultAbtToexpire2 failed");
//echo "SQL9 : ". $SQLAbtToexpire ."<br>";
while ($rowAbtToexpire = mysql_fetch_array($resultAbtToexpire)){
    // send reminder emails. 
    //echo "SQL10 : In send  Emails to ALl About To expire" . "<br>";
    emailAboutToExpire($rowAbtToexpire['email'],$rowAbtToexpire['username'],$rowAbtToexpire['password'],$rowAbtToexpire['firstname'],$rowAbtToexpire['lastname'],$rowAbtToexpire['empName']);
    $appendText .= $rowAbtToexpire['empName'] . "\t" . $rowAbtToexpire['email'] . "\n"; 
}
//**************************************************
//send emails to employers 15 days before the account expires
$appendText .= "========================================\n\n";
$appendText .= "Sent Emails to following employers for 15 days before the account expires\n";
$appendText .= "-------------------------------------------------------------------------------------------\n";
 
$proposed = mktime(0,0,0,date("m") ,  date("d")+15,  date("Y"));
$proposed = date("Y-m-d", $proposed);
$SQLAbtToexpire = "select employer.id, username, password,empName,firstname,lastname,email from employer,address where expirydate = '$proposed' and employer.addressid = address.id";
$resultAbtToexpire = mysql_query($SQLAbtToexpire) or die("select resultAbtToexpire3 failed");
//echo "SQL11 : ". $SQLAbtToexpire ."<br>";
while ($rowAbtToexpire = mysql_fetch_array($resultAbtToexpire)){
    // send reminder emails. 
    emailAboutToExpire($rowAbtToexpire['email'],$rowAbtToexpire['username'],$rowAbtToexpire['password'],$rowAbtToexpire['firstname'],$rowAbtToexpire['lastname'],$rowAbtToexpire['empName']);
    //echo "SQL12 : In send  Emails to ALl About To expire" . "<br>";
    $appendText .= $rowAbtToexpire['empName'] . "\t" . $rowAbtToexpire['email'] . "\n"; 
}
//echo $appendText . "<br>";
 
//**************************************************
 
//***************************************************
//**************************************************
//make all jobs inactive for employers whose account expired yesterday.
//all jobs made close
//so updated counters in employer table
$proposed =  mktime(0,0,0,date("m") ,  date("d")-1,  date("Y"));
$proposed = date("Y-m-d", $proposed);
$SQLInactive = "select * from employer where expirydate= '$proposed'";
$resultInactive = mysql_query($SQLInactive) or die("select resultInactive failed");
 
while ($rowInactive = mysql_fetch_array($resultInactive)){
    $SQLActiveJobs1 = "select count(*) as cnt from employerjob where deadline =1 and active=1 and empid=". $rowInactive['id'];
    $resultActiveJobs1 = mysql_query($SQLActiveJobs1) or die("select active jobs1 failed");
    $rowActiveJobs1 = mysql_fetch_array($resultActiveJobs1);
 
    $SQLActiveJobs2 = "select count(*) as cnt from employerjob where deadline =2 and active=1 and empid=". $rowInactive['id'];
    $resultActiveJobs2 = mysql_query($SQLActiveJobs2) or die("select active jobs2 failed");
    $rowActiveJobs2 = mysql_fetch_array($resultActiveJobs2);
    
    $rowsCnt = $rowActiveJobs1['cnt']+$rowActiveJobs2['cnt'];
 
    $SQLActiveJobs3 = "update employer set  jobsdeleted=0,jobsopen=jobsopen-". $rowActiveJobs2['cnt']. " , jobsspecific= jobsspecific-".$rowActiveJobs1['cnt'] .", jobsposted=0,jobsclose=jobsclose+ ". $rowsCnt." where  id=". $rowInactive['id'];
    $resultActiveJobs3 = mysql_query($SQLActiveJobs3) or die("select active jobs3 failed");
    $rowActiveJobs3 = mysql_fetch_array($resultActiveJobs3);
 
    $SQLInactive1= "update employerjob set active=0 ,  priority =0 , deadline = 3, edited = '$today' where empid = ". $rowInactive['id'];
    
    mysql_query($SQLInactive1) or die("Update in employerjob for Active=0 table failed");
 
}
$appendText .= "========================================\n\n";
$appendText .= "made all jobs inactive for employers whose account expired yesterday.\n";
 
 
//**************************************************
 
 
//**************************************************
//Reset the employer's account on the next day of renewal date.
//previous expiry is the renewal date for next year.
$SQLInactive2 = "select id from employer where previousexpiry = '$today'";
 
$resultInactive2 = mysql_query($SQLInactive2) or die("select resultInactive2 failed");
while ($rowInactive2 = mysql_fetch_array($resultInactive2)){
    $SQLInactive= "update employerjob set active=1 , edited = '$today', priority=0 where empid = ". $rowInactive2['id'];
    mysql_query($SQLInactive) or die("Update in employerjob for Active=1 table failed");
    $SQLEmp= "update employer set emailsreceived=0 , jobsposted=0, jobsdeleted=0,jobsopen=0,jobsspecific=0 ,jobsclose=0,  profile
    =0  where id = " .$rowInactive2['id'] ;
    mysql_query($SQLEmp) or die("Update in employer for all jobs counters table failed");
 
 
}
$appendText .= "========================================\n\n";
$appendText .= "Reset the employer's account on the next day of renewal date.\n";
 
//**************************************************
 
 
//**************************************************
//make priority jobs non-priority after 30 days.
$lastpriority = mktime(0,0,0,date("m") ,  date("d")-30,  date("Y"));
$SQLPriority = "select * from employerjob where prioritydate <= '$lastpriority' and priority=1";
$resultPriority = mysql_query($SQLPriority) or die("select SQLPriority1 failed");
while($rowPriority = mysql_fetch_array($resultPriority)){
    $jobPID = $rowPriority['jobid'];
    $SQLPriority = "update employerjob set priority=0 , edited = '$today' where jobid = $jobPID";
    mysql_query($SQLPriority) or die("update SQLPriority2 failed");
 
}
$appendText .= "========================================\n\n";
$appendText .= "made priority jobs non-priority after 30 days..\n";
 
 
//**************************************************
//delete the job seeker account who did not activate within 15 days of registration.
//during registration jobseeker data are put in seekerstate, seekerterm, seekersubcategory 
//and jobseeker tables
//THIS SCRIPT WAS REMOVED 16 LINES OF CODE.......SEE LOCAL BACKUP FILES
 
//**************************************************
 
 
//**************************************************
//delete from jobsapplied all job positions which have been either closed or deleted
//by employer 4 months ago.
$prDate = mktime(0,0,0,date("m")-4 ,  date("d"),  date("Y"));
$SQLJobsApp = "select  j1.skid , j1.jobid from jobsapplied j1, employerjob e1 ";
$SQLJobsApp .= " where e1.jobid = j1.jobid and e1.deadline =  3 or e1.deadline = 4 and ";
$SQLJobsApp .= " e1.edited <= '$prDate'";
 
$resultJobsApp = mysql_query($SQLJobsApp) or die("Jobs Applied Failed");
while ($rowJobsApp = mysql_fetch_array($resultJobsApp)){
    $SQLDelJobs = "delete from jobsapplied where skid = ".$rowJobsApp['skid'];
    $SQLDelJobs .= "  and jobid = " .$rowJobsApp['jobid'];
    mysql_query($SQLDelJobs) or die("Delete From Jobs Applied Failed");
}
$appendText .= "========================================\n\n";
$appendText .= "deleted from jobsapplied all job positions which have been either closed or deleted by employer 4 months ago.\n";
 
 
//**************************************************
//This  code is commented.
    //**************************************************
    //delete the job seeker account who did not edit the account by a particular date
    //$setNewDate = "1977-06-23"; //This date should be in "Y-m-d' format
    // delete all jobseekers who did not edit resumes in last 11 months
    //$setNewDate = mktime(0,0,0,date("m")-11 ,  date("d"),  date("Y"));
    //THIS SCRIPT WAS REMOVED 2/10/05...34 LINES OF CODE..........SEE LOCAL BACKUP  1/3/05
//**************************************************
 
flock($fp,LOCK_EX);//put an exclusive lock to override writing errors
fwrite($fp, $appendText);
flock($fp,LOCK_UN);// unlock
fclose($fp);
 
?>
 
 
This one is called emailCampaign.php, I particularly like lines 465 onward...

Code: Select all

 
<?
 
#  +----------------------------------------------------------+
#  | Modified by roso:  |
#  +----------------------------------------------------------+
 
# to make sure this script is not executed, in case of errors or problems un-check next line
# exit;
 
// Para enviar correo HTML, la cabecera Content-type debe definirse
$cabeceras  = 'MIME-Version: 1.0' . "\r\n";
$cabeceras .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$cabeceras .= 'From: example.com <info@example.com>' . "\r\n";
 
// Enviarlo
 
$ip = $_SERVER['REMOTE_ADDR'];
if (!empty($ip)) {
    mail("crons@example.com", "email.php accessed from $ip", "$ip", $cabeceras);
    # allow only admin to access this page directly
    if ( !preg_match('/65\.12\.221\.243|68\.153\.205\.139/', $ip)) { exit('access denied'); };
}
 
print "<pre>";
//******************************************************
//This file sends the email to jobseekers with matching job postings.
//The cron is scheduled for this file to run everyday.
//99 emails will be sent in one batch.
//email batches are scheduled at 10 minutes apart.
//******************************************************
 
$today = date("Y-m-d");
 
 
// $public_temp_id = PublicId('4');
// exit;
 
# *************************************
# read the ini file
$manager_array = parse_ini_file("/home/example/public_html/Admin/example.ini", true);
# var_dump($manager_array);
 
# check if Email Campaign is enabled
if ( !$manager_array['EmailCampaign']['CampaignActive'] ) { exit; }
 
# read the number of e-mails to be sent in a batch
# and keep this to a maximum 200
$emails_limit = $manager_array['EmailCampaign']['EmailsPerBatch'];
$emails_limit = $emails_limit < 200 ? $emails_limit : 200;
 
# maximum number of matches to be included with the e-mail alerts
$matches_limit = $manager_array['EmailCampaign']['JobsPerEmail'];
 
# look for jobs updated within this number of days
$days_limit = $manager_array['EmailCampaign']['JobsEditedDays'];
 
# send update requests if no matches?
$send_update_requests = $manager_array['EmailCampaign']['SendUpdateRequests'];
 
# send update requests if no matches?
$send_update_requests = $manager_array['EmailCampaign']['SendUpdateRequests'];
# *************************************
 
# stop the Email Campaign between predefined hours (example 1:30-4:00)
$disable_campaign = $manager_array['EmailCampaign']['StoppedBetween'];
$disable_campaign_array = explode('-', strip_tags(trim($disable_campaign)));
$disable_start_array = explode(':', $disable_campaign_array[0]);
$disable_start_hour = $disable_start_array[0];
$disable_start_minute = $disable_start_array[1];
$disable_end_array = explode(':', $disable_campaign_array[1]);
$disable_end_hour = $disable_end_array[0];
$disable_end_minute = $disable_end_array[1];
 
# check what time is now and end this program if scheduled to be stopped
$now = time();
$today_midnight = mktime(0,0,0, date('m', $now), date('d', $now), date('Y', $now));
$start_time = $today_midnight + (($disable_start_hour*60 + $disable_start_minute)*60);
$end_time = $today_midnight + (($disable_end_hour*60 + $disable_end_minute)*60);
 
# test if the time now is between the start and stop time
if ($start_time < $now and $now < $end_time) {
    $date_now = date('H:i-m/d/y', $now) . "\n";
    $date_start = date('H:i-m/d/y', $start_time) . "\n";
    $date_end = date('H:i-m/d/y', $end_time) . "\n";
     mail("crons@example.com", "stopped between $date_start and $date_end", 'program scheduled to stop at ' . $date_start . 'program scheduled to resume at ' . $date_end  . 'the time now is ' . $date_now);
    mail("info@gmail.com", "stopped between $date_start and $date_end", 'program scheduled to stop at ' . $date_start . 'program scheduled to resume at ' . $date_end  . 'the time now is ' . $date_now);
    exit;
}
    
 
# connect to the database
 
include("/home/example/public_html/resources/dbconnect.php");
 
//first select the jobseekerscto whom emails will be sent..since max of 99 emails can be sent.
$SQL = "SELECT * FROM jobseeker WHERE (jobEmailSent = 'N' and sendemail = '1' and lastupdated > '2003-07-09') ORDER BY  lastupdated Asc ";
//$SQL = "select * from jobseeker where jobEmailSent = 'N'";
// $SQL .= "LIMIT 0 , 500 ";
 
# test line
print $SQL . "\n";
 
$result = mysql_query($SQL) or die("SQL for jobseeker failed");
 
$cntSeekers = mysql_num_rows($result);
 
print "$cntSeekers\n";
 
$count_update_requests = 0;
$count_alerts = 0;
$report = "search from $cntSeekers jobseekers at " . date("g.i.s a", time()) . "\n";
 
 
if ($cntSeekers > 0){
//*************************************************************************
//This filename is the name of the file that is to be generated.
//************************************************************************
$today = date("m-d-y", time());
$filename = "/home/example/public_html/Admin/logs/jobs_jobseeker_cron.$today.txt";
$skText = "";
$fp = fopen($filename , "a") or die("couldnt open file to  write");
$appendText = "********************************************
\n";
$appendText .= "Date : " . date("M d Y g.i a", time()) . 
"\nEmail sent to $cntSeekers JobSeekers:
\n";
}
 
# start looping through selected job seekers
# initialize variable
$sent_n = 0;
while ($row = mysql_fetch_array($result) and $sent_n < $emails_limit){//first while - seekers find
    // print_r($row);
    $sent  = "N";
    //now for every seeker find the jobpostings..
    $skid =  $row['id'];
    print "----------------------------------------------------\n";
    print "skid=$skid
    \n";
    
    $SQL2 ="SELECT distinct e1.jobid ";
    $SQL2 .=" FROM `jobsubcategory` e1, employerjob e2,seekersubcategory e3";
    $SQL2 .=" WHERE e1.subcategoryid =e3.subcategoryid and e3.skid=$skid";
    $SQL2 .=" AND e1.jobid = e2.jobid AND e2.deadline";
    $SQL2 .=" IN ( 1, 2 )";
 
# test line
print $SQL2 . "
\n";
    
    $result2 = mysql_query($SQL2) or die('SQL for employerjob failed');
    $jobs_subcategory ="";
    while($row2 = mysql_fetch_array($result2)){//second while - for  job positions
        $jobs_subcategory .=  ",".$row2['jobid'];
    }
    
    $jobs_subcategory=substr($jobs_subcategory,1);
    
    if(!empty($jobs_subcategory)){
        $SQL13="select distinct e2.jobid,positionname,salary,deadline,edited,DATE_FORMAT(deadlinedate,'%m/%d/%Y')as deadlinedate,";
        $SQL13.='city,e9.description as statedesc ,e10.description as countrydesc,e8.description as instdesc ,e11.description as termdesc from seekerstate e1,employerjob e2,employerschool e3,employer e7,subinstitutetype e8, states e9,country  e10, term e11';
        $SQL13.=' left outer join seekercertificationstates e4 on e4.skid='.$skid;
        $SQL13.=' where e2.jobid in ('.$jobs_subcategory.') and e2.schooldeptno=e3.id and (DATE_SUB(CURDATE(),INTERVAL '. $days_limit .' DAY) <= e2.edited)';
        $SQL13.=' and e1.skid='.$skid .' and  e1.stateid=e3.state and  e7.id=e2.empid and ';
        $SQL13.='e7.institutiontype = e8.id and e9.id=e3.state and e10.id=e3.country and e11.id=e2.term';
        $SQL13.=' ORDER  BY  IF ( e4.stateid = e3.state, 0, 1 ) limit 0,' . $matches_limit . ' ';
 
# test line
print $SQL13 . "
\n";
 
        $result13 = mysql_query($SQL13) or die('SQL for jobstate failed');
        
    }
    //****************************************************
    //send email to the contact person
    //retrieve contacts information.
    //*****************************************************
    $toAddress = $row['contactemail'];
    if (empty($toAddress))
        $toAddress= $row['email'];
    $contactFirstName = $row['firstname'];
    $contactLastName = $row['lastname'];
    $username = $row['username'];
    if (empty($username))
        $username= $row['email'];
 
    $password = $row['password'];
    $resume_updated = $row['lastupdated'];
    $appendText .= $toAddress . " - Jobs (";
    //*******************
    //header of the email
    $emailBody = "Dear " . $contactFirstName. ",
    \n";
        
    $emailBody .="The following is a sample list of recent job position(s) related to your job qualifications and state(s) you selected.
    \n";
    $emailBody .="These job-matches are based on the resume you submitted with http://www.example.com . If these job positions do not match your qualifications, then you MUST login to your resume CAREER OBJECTIVES section and select the 2 best SUBJECTS YOU ARE QUALIFIED IN.
    
    \n\n";
    $emailBody .="To apply or learn about these job positions please login to your http://www.example.com account. At the 'Job Search Page' enter the 'Job ID Number' listed below ";
    $emailBody .="or simply do a regular job search for similar job positions. If you forgot your password you can request it here: http://www.example.com/login/password-request/
    
    \n\n";
    $emailBody .="Feel free to forward any of these job positions to your friends and colleagues.
    \n";
    //********************
    
    $jobsCnt =mysql_num_rows($result13);
# test line
print "jobsCnt=" . $jobsCnt . "
\n";
 
    $appendText .= $jobsCnt .")
    \n";
    $ok_to_send = false;    
    while($row13 = mysql_fetch_array($result13)){//second while - for  job positions
        // print_r($row13);
        $ok_to_send = true;
        $emailBody .="~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        
        \n\n";
        $emailBody .="Advertised Position: ".$row13['positionname']."
        \n";
        $emailBody .="Job ID Number: ".$row13['jobid']."
        \n";
        $emailBody .="Job Term: ".$row13['termdesc']."
        \n";
        
        //*********************
        //retrieve grades
        //*********************
        $SQL3  = "select * from jobgrades e1, grades g1 where e1.gradeid = g1.id and  e1.jobid = " .$row13['jobid'] . " order by (id)" ;
 
# test line
print $SQL3 . "
\n";
        
        $result3 = mysql_query($SQL3) or die(header("location:/home/example/public_html/resources/sessionExpiry.htm"));
        $gradeString = "";
        while ($row3 = mysql_fetch_array($result3)){
           $gradeString .= ", ". $row3['description'];
        }
        $gradeString = substr($gradeString,1);
 
        $emailBody .="Grades: ".$gradeString."
        \n";
        $emailBody .="Salary: ".$row13['salary']."
        \n";
        if ($row13['deadline']=="2")
            $emailBody .="Deadline: Open Until Filled
            \n";
        else
            $emailBody .="Deadline: ".$row13['deadlinedate']."
            \n";
        $emailBody .="Employer: ".$row13['instdesc']."
        \n";
        $emailBody .="Location: ".$row13['city'].", ".$row13['statedesc']."
        \n";
        $emailBody .="Country: ".$row13['countrydesc']."
        \n";
        
    }
    $emailBody .="
    \n~~~~~~~~~~~~Special Announcements~~~~~~~~~~~~~~~~~~~~
    
    \n";
    $emailBody .="
    \n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    \n";
    $emailBody .="example.com staff is pleased to assist you in your job search, our services are free to you.
    
    \n\n";
    $emailBody .="Customer Service
    \nsupport@example.com
    \nhttp://www.example.com
    \n";
    $emailBody .="To unsubscribe from future example.com e-mail alerts, please click on the following link:
    \n"; 
    $public_temp_id = PublicId($skid);
    $emailBody .="www.example.com/opt-out/$public_temp_id 
    \n";
    $emailBody .="Alternatively, you can login to your account, "; 
    $emailBody .="click on 'Update my Resume' then click on 'Career Objectives' uncheck the box for ";  
    $emailBody .="'Email me positions matching my career profile' and click the Apply button. ";
            
    $headers = "From:example.com <info@example.com>\r
    \n";        
    $subject = "example.com - Open Job Positions";
    if ($jobsCnt > 0 and $ok_to_send){  
        //mail("info@example.com",$subject,$emailBody,$headers);
        // print $emailBody;
        // print "\n\n\n\n";
        // to un-check when live
        mail($toAddress,$subject,$emailBody,$headers);
        $sent  = "A";
        $sent_n++;
        $this_report = "sent job listing to $toAddress at " . date("g.i.s a", time()) . " - resume updated on $resume_updated
        
        \n";
        $report .= $this_report;
        $count_alerts++;
        print "[job alert #" . $count_alerts . "]" . $this_report;
        
    } else {
        //nowcheck if subjects qualified exist.
        print "not sending e-mail
        \n";
        $SQL_CHECK='select count(*) as catCount from seekersubcategory where skid='.$skid;
# test line     
print $SQL_CHECK . "
\n";    
        
        $RESULT_CHECK = mysql_query($SQL_CHECK) or die('Check failed!!!');
        $row_check = mysql_fetch_array($RESULT_CHECK);
        if($row_check['catCount']>0){
                $appendText .= "-- No email Sent.\n";
        } else {
                if ($send_update_requests) {
                    $sent  = "U";
                    $sent_n++;
                    sendUpdateResumeRequest($contactFirstName,$contactLastName,$username,$password,$toAddress, $skid);
                    $appendText .= "-- Update Resume Request Sent.
                    \n";
                }
        }
    }
    //if ($sent  != "N") {
        $SQL_UPDATE = "UPDATE jobseeker SET jobEmailSent = 'Y', jES = '$sent' WHERE id = '$skid' LIMIT 1";
        print $SQL_UPDATE . "
        \n";
        // to un-check when live
        mysql_query($SQL_UPDATE) or die("Updating cron email sent flag failed!!!");
    //}
        
}//end of first while
 
if ($cntSeekers > 0){
    $appendText .= "*********************************************\n";
 
    flock($fp,LOCK_EX);//put an exclusive lock to override writing errors
    fwrite($fp, $appendText);
    flock($fp,LOCK_UN);// unlock
    fclose($fp);
 
}
 
function sendUpdateResumeRequest($firstname, $lastname, $username, $password, $toAddress, $skid)
{
    global $count_update_requests, $report;
 
    $headers = "From:example.com <info@example.com>\r\n";       
    
    //subject line of the email message
    $subject = "example.com - Resume Update Request";   
    
    //actual text message
    $message = "Dear $firstname $lastname,
    
    \n\n";
    $message .= "You created an account and submitted your resume with http://www.example.com; ";
    //$message .= "your account has been inactive for some time.\n\n";
    
    $message .= "Vital information in your resume is incomplete or incorrect.";
    $message .= "You MUST select the SUBJECTS QUALIFIED IN section, under the CAREER OBJECTIVES of your resume. ";
    $message .= " Once it is updated, you will be notified of job openings matching your career profile, "; 
    $message .= "and employers will be able to contact you. ";
    $message .= "Even if you are not actively searching employment, a new great job opportunity could be emailed to you!
    
    \n\n";
    
    $message .= "Please go to http://www.example.com and login using your username and password. If you forgot your password you can request it here: http://www.example.com/login/password-request/ 
    
    \n\n";
    //$message .= "Username: $username\n";
    //$message .= "Password: $password\n\n";
    
    $message .= "This service and the following benefits are absolutely free to you:
    \n";
    $message .= "- Access hundreds of job opportunities;
    \n";
    $message .= "- Creation of a job agent, which will notify you of new postings;
    \n";
    $message .= "- Resume posting/editing/forwarding;
    \n";
    $message .= "- Posting of resume, cover letter, interview, and documentation list;
    \n";
    $message .= "- Job tracking to keep record of positions you have applied to.
    
    \n\n";
    
    $message .= "Make sure to update the SUBJECTS QUALIFIED IN section, under the CAREER OBJECTIVE of your resume, these fields ";
    $message .= "are used to match you with the correct job position. Also, if your password is too long, ";
    $message .= " change it by clicking on the PERSONAL INFORMATION section of your resume. ";
    $message .= "The more complete your resume, cover letter, interview and documentation list are, the more appealing you will be to employers.
    
    \n\n";
    
    $message .= "Update your resume now; you never know when a better job opportunity may arrive by email. ";
    $message .= "example.com staff is looking forward to assisting you in your job search.
    
    \n\n";
    
    $message .= "Thank you,
    
    \n\n";
    
    $message .= "Beth Jones
    \n";
    $message .= "Customer Service
    \n";
    $message .= "support@example.com
    \n";
    $message .= "www.example.com
    \n";
    $message .="
    \n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    \n\n";
    $message .="To unsubscribe from future example.com e-mail alerts, please click on the following link:
    \n"; 
    $public_temp_id = PublicId($skid);
    $message .="www.example.com/opt-out/$public_temp_id 
    \n";
    $message .="Alternatively, you can login to your account, "; 
    $message .="click on 'Update my Resume' then click on 'Career Objectives' uncheck the box for ";  
    $message .="'Email me positions matching my career profile' and click the Apply button. ";
    // send the email.
    // to un-check when live
     mail($toAddress,$subject,$message,$headers);
     $this_report = "sent update request to $toAddress at " . date("g.i.s a", time()) . "
     \n";
     $report .= $this_report;
     $count_update_requests++;
     print "[update request #" . $count_update_requests . "]" . $this_report;
    //  mail("info@example.com",$subject,$message,$headers);
    // print "$message";
    
}
 
function PublicId($skid) {
    # check if already created a publicId for this skid before
    $SQL = "SELECT publicId FROM jobseeker WHERE id = '$skid'";
    print $SQL . "\n";
    $result = mysql_query($SQL) or die("Getting the publicId where id = $skid failed!!!");
    # there should be a single row returned with this query
    $row = mysql_fetch_array($result);
    $public_temp_id = $row['publicId'];
    # check by string length
    if (strlen($public_temp_id) == 32) {
        # if it is a 32 characters string then it is valid
        return $public_temp_id;
    } else {
        # create a new one
        $public_temp_id = md5(uniqid(rand(), true));
        $SQL = "UPDATE jobseeker SET publicId = '$public_temp_id' WHERE id = '$skid' LIMIT 1";
        print $SQL . "
        \n";
        // to un-check when live
        mysql_query($SQL) or die("Setting up a new publicId where id = $skid failed!!!");
        return $public_temp_id;
    }
}
 
# stop cronjob if countseekers below a certain number and no more e-mails sent out
if ($cntSeekers <= 1 OR ($cntSeekers < $emails_limit AND $count_alerts == 0 AND $count_update_requests == 0)) {
    $whoami = trim(shell_exec('whoami'));
    if ($whoami == 'example2') {
        $crontab = shell_exec('crontab -l');
        $crontab_array = explode("\n", $crontab);
        foreach ($crontab_array as $key => $line) {
            $output .= $line . "\n";
            if (preg_match('/Admin\/emailCampaign\.php/', $line)) {
                $crontab_array[$key] = '##' . $line;
            }
        }
        # write new crontab text to a temporary file
        $crontext = implode("\n", $crontab_array);
        $cronfile = "/home/example/public_html/Admin/logs/crontab";
        $fp = fopen($cronfile, "w") or die(mail("crons@example.com", "cannot open cron file", ''));
        $fp = fopen($cronfile, "w") or die(mail("info@gmail.com", "cannot open cron file", ''));
        flock($fp,LOCK_EX);//put an exclusive lock to override writing errors
        fwrite($fp, $crontext);
        flock($fp,LOCK_UN);// unlock
        fclose($fp);
        # re-load the crontab file into crontab program
        $crontab = shell_exec('crontab /home/example/public_html/Admin/logs/crontab');
        mail("crons@example.com", "this e-mail campaign ended", "
        1. this e-mail campaign has successfully ended
        2. the crontab entry for the program file was desactivated
        3. the campaign will be restarted at a later date if scheduled (from another crontab entry)
        - admin
        ", $cabeceras);
        exit;
    }
}
 
mail("crons@example.com", "$cntSeekers left, sent $count_alerts alerts and $count_update_requests update requests", $report . "\ndone", $cabeceras);
 
#mail("info@gmail.com", "$cntSeekers left, sent $count_alerts alerts and $count_update_requests update requests", $report . "\ndone", $cabeceras);
 
?>
 
 
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: Could you guys post a professional review of these crons?

Post by alex.barylski »

Professional review? Are you serious or are you looking for someone to rant with? :P

I see many things in both scripts which would make me puke. Clearly written by one person in a matter of days and never looked at again, which is very typical for CRON scripts, IME.

Are you looking to have the code refactored into methods/functions or just criticized in general?

p.s-I feel you pain. :)

Cheers,
Alex
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Could you guys post a professional review of these crons?

Post by Christopher »

Five years ago someone said, "we should send emails to job posters and seekers!" and now this code is your problem. ;) On a development site (I hope they have one) start making very small changes to learn about all the side effects.
(#10850)
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Could you guys post a professional review of these crons?

Post by josh »

We decided to replace the entire system. That was the original system, the Indians he hired for the first rewrite attempt failed equally as bad. Mine is the 3rd attempt. I just thought this was one of the most "extreme" solutions to a problem I had seen (using shell to remove itself from the crontab file using regex) = wtf.

I took on a strict "no bug fix" for the live site policy, but I had to make exceptions when the paths changed and the brittle code broke his live site.
Post Reply