Rewrote 'we' word a little, rewrote mail order to use SQL_INSERTID() instead of anoth...
[mailer.git] / inc / libs / forced_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 07/25/2011 *
4  * ===================                          Last change: 07/25/2011 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : forced_functions.php                             *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for ext-forced                         *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer ext-forced                       *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Translate forced ad type
44 function translateForcedAdsType ($status) {
45         // Is the status null or empty?
46         if (is_null($status)) {
47                 // Is NULL
48                 $status = 'NULL';
49         } elseif (empty($status)) {
50                 // Is empty (string)
51                 $status = 'EMPTY';
52         } // END - if
53
54         // Default status is unknown
55         $return = '{%message,ADMIN_FORCED_ADS_TYPE_UNKNOWN=' . $status . '%}';
56
57         // Construct message id
58         $messageId = 'ADMIN_FORCED_ADS_TYPE_' . $status;
59
60         // Is it there?
61         if (isMessageIdValid($messageId)) {
62                 // Then use it as message string
63                 $return = '{--' . $messageId . '--}';
64         } // END - if
65
66         // Return the status
67         return $return;
68 }
69
70 // Translate forced campaign status
71 function translateForcedCampaignStatus ($status) {
72         // Is the status null or empty?
73         if (is_null($status)) {
74                 // Is NULL
75                 $status = 'NULL';
76         } elseif (empty($status)) {
77                 // Is empty (string)
78                 $status = 'EMPTY';
79         } // END - if
80
81         // Default status is unknown
82         $return = '{%message,ADMIN_FORCED_CAMPAIGN_TYPE_UNKNOWN=' . $status . '%}';
83
84         // Construct message id
85         $messageId = 'ADMIN_FORCED_CAMPAIGN_TYPE_' . $status;
86
87         // Is it there?
88         if (isMessageIdValid($messageId)) {
89                 // Then use it as message string
90                 $return = '{--' . $messageId . '--}';
91         } // END - if
92
93         // Return the status
94         return $return;
95 }
96
97 // Translate visibility
98 function translateForcedCostsVisibility ($visibility) {
99         // Is the status null or empty?
100         if (is_null($visibility)) {
101                 // Is NULL
102                 $visibility = 'NULL';
103         } elseif (empty($visibility)) {
104                 // Is empty (string)
105                 $visibility = 'EMPTY';
106         } // END - if
107
108         // Default status is unknown
109         $return = '{%message,ADMIN_FORCED_ADS_VISIBILITY_UNKNOWN=' . $visibility . '%}';
110
111         // Construct message id
112         $messageId = 'ADMIN_FORCED_ADS_VISIBILITY_' . $visibility;
113
114         // Is it there?
115         if (isMessageIdValid($messageId)) {
116                 // Then use it as message string
117                 $return = '{--' . $messageId . '--}';
118         } // END - if
119
120         // Return the status
121         return $return;
122 }
123
124 // "Getter" for an array of data from all Forced-PopUps except user's
125 function getForcedPopupDataByEarningArray ($content) {
126         die('content=<pre>' . print_r($content, true) . '</pre>' . debug_get_printable_backtrace());
127
128         // Finally return the content
129         return $content;
130 }
131
132 // Generator (somewhat getter) for forced-ads type options
133 function generateForcedAdsTypeOptions ($type =  NULL) {
134         // Is this cached?
135         if (!isset($GLOBALS[__FUNCTION__][$type])) {
136                 // Generate output and cache it
137                 $GLOBALS[__FUNCTION__][$type] = generateOptions(
138                         '/ARRAY/',
139                         array(
140                                 'BANNER',
141                                 'TEXTLINK',
142                                 'POPUP',
143                         ),
144                         array(),
145                         $type,
146                         '', '',
147                         array(),
148                         'translateForcedAdsType'
149                 );
150         } // END - if
151
152         // Return content
153         return $GLOBALS[__FUNCTION__][$type];
154 }
155
156 // Generator (somewhat getter) for forcec-costs visibility options
157 function generateForcedCostsVisibilityOptions ($visibility =  NULL) {
158         // Is this cached?
159         if (!isset($GLOBALS[__FUNCTION__][$visibility])) {
160                 // Generate output and cache it
161                 $GLOBALS[__FUNCTION__][$visibility] = generateOptions(
162                         '/ARRAY/',
163                         array(
164                                 'ALL',
165                                 'MEMBER',
166                                 'SPONSOR',
167                                 'NONE'
168                         ),
169                         array(),
170                         $visibility,
171                         '', '',
172                         array(),
173                         'translateForcedCostsVisibility'
174                 );
175         } // END - if
176
177         // Return content
178         return $GLOBALS[__FUNCTION__][$visibility];
179 }
180
181 // "Getter" for an array of all given forced ads
182 function getArrayFromForcedAdsByType ($forcedType = NULL) {
183         // Init array
184         $forcedAds = array();
185
186         // Init WHERE (default)
187         $where = '';
188
189         // Is forced type not NULL?
190         if (!is_null($forcedType)) {
191                 // Then set proper WHERE
192                 $where = sprintf("WHERE `forced_ads_type`='%s'", SQL_ESCAPE($forcedType));
193         } // END - if
194
195         // Search all given types
196         $result = SQL_QUERY('SELECT
197         `forced_ads_id`,
198         `forced_ads_ad_url`,
199         `forced_ads_click_url`,
200         `forced_ads_width`,
201         `forced_ads_height`,
202         `forced_ads_alt_text`,
203         `forced_ads_framebreaker`,
204         `forced_ads_type`,
205         `forced_ads_views_counter`,
206         `forced_ads_clicks_counter`,
207         UNIX_TIMESTAMP(`forced_ads_added`) AS `forced_ads_added`,
208         `forced_ads_userid`
209 FROM
210         `{?_MYSQL_PREFIX?}_forced_ads`
211 ' . $where . '
212 ORDER BY
213         `forced_ads_id` ASC', __FUNCTION__, __LINE__);
214
215         // Is there at least one entry?
216         if (!SQL_HASZERONUMS($result)) {
217                 // Get all elements
218                 while ($content = SQL_FETCHARRAY($result)) {
219                         // Add it
220                         $forcedAds[$content['forced_ads_id']] = $content;
221                 } // END - while
222         } // END - if
223
224         // Free result
225         SQL_FREERESULT($result);
226
227         // Return it
228         return $forcedAds;
229 }
230
231 // "Getter" for an array of all forced costs from given visibility or all
232 function getArrayFromForcedCostsByVisibility ($visibility = NULL) {
233         // Init array
234         $forcedCosts = array();
235         $where = '';
236
237         // Is visibility not NULL?
238         if (!is_null($visibility)) {
239                 // Then add WHERE statement
240                 $where = sprintf(" WHERE `forced_costs_visibility`='%s'", SQL_ESCAPE($visibility));
241         } // END - if
242
243         // Search all given types
244         $result = SQL_QUERY("SELECT
245         `forced_costs_id`,
246         `forced_costs_price_click`,
247         `forced_costs_payment_click`,
248         `forced_costs_visibility`
249 FROM
250         `{?_MYSQL_PREFIX?}_forced_costs`
251 ".$where."
252 ORDER BY
253         `forced_costs_id` ASC", __FUNCTION__, __LINE__);
254
255         // Is there at least one entry?
256         if (!SQL_HASZERONUMS($result)) {
257                 // Get all elements
258                 while ($content = SQL_FETCHARRAY($result)) {
259                         // Add it
260                         $forcedCosts[$content['forced_costs_id']] = $content;
261                 } // END - while
262         } // END - if
263
264         // Free result
265         SQL_FREERESULT($result);
266
267         // Return it
268         return $forcedCosts;
269 }
270
271 // "Getter" for an array of all forced campaigns from given array and status
272 function getArrayFromForcedCampaignsByArray ($ids, $status) {
273         // Init array
274         $forcedCampaigns = array();
275
276         // Search all given types
277         $result = SQL_QUERY_ESC("SELECT
278         `forced_campaign_id`,
279         UNIX_TIMESTAMP(`forced_campaign_created`) AS `forced_campaign_created`,
280         `forced_campaign_status`,
281         UNIX_TIMESTAMP(`forced_campaign_last_locked`) AS `forced_campaign_last_locked`,
282         `forced_campaign_lock_reason`,
283         `forced_campaign_expired`,
284         `forced_campaign_ordered_clicks`,
285         `forced_campaign_payment_api`,
286         `forced_campaign_reload_lock`,
287         `forced_campaign_minimum_stay`,
288         `forced_ads_id`,
289         `forced_campaign_userid`,
290         `forced_costs_id`
291 FROM
292         `{?_MYSQL_PREFIX?}_forced_campaigns`
293 WHERE
294         `forced_campaign_id` IN (%s) AND
295         `forced_campaign_status`='%s'
296 ORDER BY
297         `forced_campaign_id` ASC",
298                 array(
299                         implode(', ', $ids),
300                         $status
301                 ), __FUNCTION__, __LINE__);
302
303         // Is there at least one entry?
304         if (!SQL_HASZERONUMS($result)) {
305                 // Get all elements
306                 while ($content = SQL_FETCHARRAY($result)) {
307                         // Add it
308                         $forcedCampaigns[$content['forced_campaign_id']] = $content;
309                 } // END - while
310         } // END - if
311
312         // Free result
313         SQL_FREERESULT($result);
314
315         // Return it
316         return $forcedCampaigns;
317 }
318
319 // "Activates" forced campaigns from POST data
320 function doForcedAdminActivateCampaigns () {
321         // Do some sanity checks
322         if (!isAdmin()) {
323                 // Not allowed to call
324                 return false;
325         } elseif (countPostSelection('forced_campaign_id') == 0) {
326                 // No selections made
327                 return false;
328         }
329
330         // Get an array from all pending campaigns
331         $forcedCampaigns = getArrayFromForcedCampaignsByArray(array_keys(postRequestElement('forced_campaign_id')), 'PENDING');
332
333         // By default all worked (at this point)
334         $activated = true;
335
336         // Run through all entries
337         foreach ($forcedCampaigns as $campaignId => $campaignData) {
338                 // Change the status of this campaign
339                 if (!changeForcedCampaignStatus($campaignId, 'PENDING', 'ACTIVE', $campaignData)) {
340                         // One didn't work, but continue with others
341                         $activated = false;
342                 } // END - if
343         } // END - foreach
344
345         // Return status
346         return $activated;
347 }
348
349 // Changes the status of a forced campaign from previous to new status
350 function changeForcedCampaignStatus ($campaignId, $prevStatus, $newStatus, $data) {
351         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'campaignId=' . $campaignId . ',prevStatus=' . $prevStatus . ',data[]=' . gettype($data) . ',newStatus=' . $newStatus . ' - ENTERED!');
352         // Make new status always lower-case
353         $newStatus = strtolower($newStatus);
354
355         // Prepare array
356         $filterData =  array(
357                 'campaign_id' => $campaignId,
358                 'prev_status' => $prevStatus,
359                 'new_status'  => $newStatus,
360                 'data'        => $data,
361                 'abort'       => NULL
362         );
363
364         // Run pre filter chain
365         $filterData = runFilterChain('pre_change_forced_campaign_status', $filterData);
366
367         // Abort here?
368         if (!is_null($filterData['abort'])) {
369                 // Abort here
370                 return $filterData['abort'];
371         } // END - if
372
373         // Update the status now
374         // ---------- Comment out for debugging/developing member actions! ---------
375         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_forced_campaigns` SET `forced_campaign_status`='%s' WHERE `forced_campaign_id`=%s LIMIT 1",
376                 array(
377                         $newStatus,
378                         bigintval($campaignId)
379                 ), __FUNCTION__, __LINE__);
380         // ---------- Comment out for debugging/developing member actions! ---------
381
382         // Was that fine?
383         // ---------- Comment out for debugging/developing member actions! ---------
384         if (SQL_AFFECTEDROWS() != 1) {
385                 // No, something went wrong
386                 return false;
387         } // END - if
388         // ---------- Comment out for debugging/developing member actions! ---------
389
390         // Run post filter chain
391         $filterData = runFilterChain('post_change_forced_campaign_status', $filterData);
392
393         // Check if generic 'data' is there
394         assert(isset($filterData['data']));
395
396         // All done!
397         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'campaignId=' . $campaignId . ',prevStatus=' . $prevStatus . ',newStatus=' . $newStatus . ' - EXIT!');
398         return true;
399 }
400
401 // Notify admin(s) with a selected message and content
402 function doForcedNotifyAdmin ($messageType, $content) {
403         // Prepare template name
404         $templateName = sprintf("admin_forced_%s", $messageType);
405
406         // Prepare subject
407         $subject = sprintf("{--ADMIN_FORCED_NOTIFY_%s_SUBJECT--}",
408                 strtoupper($messageType)
409         );
410
411         // Is the subject line there?
412         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
413                 // Set default subject if following eval() wents wrong
414                 $subject = '{%message,ADMIN_FORCED_NOTIFY_DEFAULT_SUBJECT=' . strtoupper($messageType) . '%}';
415         } // END - if
416
417         // Translate some data if present
418         $content = prepareForcedContentForTemplate($content);
419
420         // Send the notification out
421         return sendAdminNotification($subject, $templateName, $content, $content['forced_campaign_userid']);
422 }
423
424 // Notify the user about the performed action
425 function doForcedNotifyMember ($messageType, $content) {
426         // Skip notification if userid is NULL
427         if (is_null($content['forced_campaign_userid'])) {
428                 // NULL is silently ignored
429                 return true;
430         } // END - if
431
432         // Prepare template name
433         $templateName = sprintf("member_forced_%s", $messageType);
434
435         // Prepare subject
436         $subject = sprintf("{--MEMBER_FORCED_NOTIFY_%s_SUBJECT--}",
437                 strtoupper($messageType)
438         );
439
440         // Is the subject line there?
441         if ((substr($subject, 0, 1) == '!') && (substr($subject, -1, 1) == '!')) {
442                 // Set default subject if following eval() wents wrong
443                 $subject = '{--MEMBER_FORCED_NOTIFY_DEFAULT_SUBJECT--}';
444         } // END - if
445
446         // Translate some data if present
447         $content = prepareForcedContentForTemplate($content);
448
449         // Load template
450         $mailText = loadEmailTemplate($templateName, $content, $content['forced_campaign_userid']);
451
452         // Send the email
453         return sendEmail($content['forced_campaign_userid'], $subject, $mailText);
454 }
455
456 // Translates some data for template usage
457 // @TODO Can't we use our new expression language instead of this ugly code?
458 function prepareForcedContentForTemplate ($content) {
459         // Prepare some code
460         if (isset($content['forced_campaign_created'])) $content['forced_campaign_created'] = generateDateTime($content['forced_campaign_created'], 2);
461
462         // Return translated content
463         return $content;
464 }
465
466 // ----------------------------------------------------------------------------
467 //                            Template helper functions
468 // ----------------------------------------------------------------------------
469
470 // Template helper function to create selection box for all forced-ad types
471 function doTemplateForcedAdTypeSelectionBox ($templateName, $clear = false, $default = NULL) {
472         // Add all types through the filter
473         $forcedAdTypes = runFilterChain('add_forced_ads_types', array());
474
475         // Handle it over to generateSelectionBoxFromArray()
476         $content = generateSelectionBoxFromArray($forcedAdTypes, 'forced_ads_type', 'type', '', '', '', $default);
477
478         // Return prepared content
479         return $content;
480 }
481
482 // Template helper function to create selection box for costs visibility
483 function doTemplateForcedCostsVisiblitySelectionBox ($templateName, $clear = false, $default = NULL) {
484         // Init array
485         $costsVisibility = array(
486                 0 => array('visibility' => 'ALL'),
487                 1 => array('visibility' => 'MEMBER'),
488                 2 => array('visibility' => 'SPONSOR'),
489                 3 => array('visibility' => 'NONE')
490         );
491
492         // Handle it over to generateSelectionBoxFromArray()
493         $content = generateSelectionBoxFromArray($costsVisibility, 'forced_costs_visibility', 'visibility', '', '', '', $default);
494
495         // Return prepared content
496         return $content;
497 }
498
499 // Template helper function to create selection box for foreced ads
500 function doTemplateForcedAdSelectionBox ($templateName, $clear, $default = NULL) {
501         // Get back an array of all forced popups
502         $forcedAds = getArrayFromForcedAdsByType();
503
504         // Handle it over to generateSelectionBoxFromArray()
505         $content = generateSelectionBoxFromArray($forcedAds, 'forced_ads_id', 'forced_ads_id', '', '', '', $default, 'forced_ads_type');
506
507         // Return prepared content
508         return $content;
509 }
510
511 // Template helper function to create selection box for foreced costs
512 function doTemplateForcedCostsSelectionBox ($templateName, $clear, $default = NULL) {
513         // Get back an array of all forced popups
514         $forcedCosts = getArrayFromForcedCostsByVisibility();
515
516         // Handle it over to generateSelectionBoxFromArray()
517         $content = generateSelectionBoxFromArray($forcedCosts, 'forced_costs_id', 'forced_costs_id', '', '', '', $default, '', true);
518
519         // Return prepared content
520         return $content;
521 }
522
523 // Template helper function to create selection box for foreced campaign userid
524 function doTemplateForcedCampaignUseridSelectionBox ($templateName, $clear, $default = NULL) {
525         // Generate the selection box without all
526         $content = addMemberSelectionBox($default, false, true, true, 'forced_campaign_userid');
527
528         // Return prepared content
529         return $content;
530 }
531
532 // ----------------------------------------------------------------------------
533 //                             XML call-back functions
534 // ----------------------------------------------------------------------------
535
536 // For 'doing' add forced-ads, the column-index is required
537 function addXmlSpecialAdminAddDoForcedAds () {
538         // So set it all here
539         $GLOBALS['__COLUMN_INDEX']['doXmlCallbackFunction']  = 'column';
540         $GLOBALS['__XML_ARGUMENTS']['doXmlCallbackFunction']['extra_values'] = array();
541         $GLOBALS['__XML_ARGUMENTS']['doXmlCallbackFunction']['column_index'] = 'column';
542 }
543
544 // For 'doing' add forced-campaigns, the column-index is required
545 function addXmlSpecialAdminAddDoForcedCampaigns () {
546         // So set it all here
547         $GLOBALS['__COLUMN_INDEX']['doXmlCallbackFunction']  = 'column';
548         $GLOBALS['__XML_ARGUMENTS']['doXmlCallbackFunction']['column_index'] = 'column';
549 }
550
551 // For 'doing' add forced-costs, the column-index is required
552 function addXmlSpecialAdminAddDoForcedCosts () {
553         // So set it all here
554         $GLOBALS['__COLUMN_INDEX']['doXmlCallbackFunction']  = 'column';
555         $GLOBALS['__XML_ARGUMENTS']['doXmlCallbackFunction']['extra_values'] = array();
556         $GLOBALS['__XML_ARGUMENTS']['doXmlCallbackFunction']['column_index'] = 'column';
557 }
558
559 // [EOF]
560 ?>